//
//  TPHomeViewPageController.m
//  XTCloud
//
//  Created by QA on 2017/8/24.
//  Copyright © 2017年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "TPHomePageViewController.h"
#import "MYSegmentView.h"
#import "CarQueryHomeViewCell.h"
#import "CPTouchTableTableView.h"

#import "TPHomeItemViewController.h"
#import "CircleProgressView.h"
#import "CATCurveProgressView.h"

#import "WebServiceCommonRequest.h"
#import "NSDictionary+DataFormat.h"
#import "DateTimeFormat.h"

@interface TPHomePageViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong) IBOutlet UIView *headImageView;
@property(nonatomic ,strong) CPTouchTableTableView *mainTableView;
@property (nonatomic, strong) MYSegmentView *RCSegView;

@property (strong, nonatomic) NSMutableArray *firstResultData;
@property (strong, nonatomic) NSMutableArray *rwdResultData;

@property (nonatomic,strong) IBOutlet UILabel *JHFLLabel;
@property (nonatomic,strong) IBOutlet UILabel *FHFLLabel;
@property (nonatomic,strong) IBOutlet UILabel *RWDSLabel;
@property (nonatomic,strong) IBOutlet UILabel *QSFLLabel;
@property (nonatomic,strong) IBOutlet UILabel *ZCCLabel;
@property (nonatomic,strong) IBOutlet UILabel *LTCCLabel;
@property (nonatomic,strong) IBOutlet UILabel *SJCCLabel;
@property (nonatomic,strong) IBOutlet UILabel *LSCCLabel;
@property (weak, nonatomic) IBOutlet CATCurveProgressView *loopProgressView;

@property (nonatomic, assign) CGFloat headViewHeight;
@property (nonatomic, assign) BOOL canScroll;
@property (nonatomic, assign) BOOL isTopIsCanNotMoveTabView;
@property (nonatomic, assign) BOOL isTopIsCanNotMoveTabViewPre;

@end

@implementation TPHomePageViewController
@synthesize mainTableView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self setTitle: @"实时生产看板"];
        [self addStationToNavigationItem];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.automaticallyAdjustsScrollViewInsets = NO;
    self.headViewHeight = _headImageView.bounds.size.height;
    
    mainTableView= [[CPTouchTableTableView alloc] init];
    mainTableView.delegate=self;
    mainTableView.dataSource=self;
    mainTableView.showsVerticalScrollIndicator = NO;
    mainTableView.contentInset = UIEdgeInsetsMake(self.headViewHeight, 0, 0, 0);
    //mainTableView.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.mainTableView];
    [mainTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view);
        make.right.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.view);
    }];
    
    [self.mainTableView addSubview:self.headImageView];
    self.headImageView.frame = CGRectMake(0, 0, SuperWidth, self.headViewHeight);
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(acceptMsg:) name:@"leaveTop" object:nil];
    
    CGRect f = self.headImageView.frame;
    f.origin.y= -self.headViewHeight;
    self.headImageView.frame= f;
    
    //获取页面显示数据
    [self getNetworkBaseData];
}

-(void)acceptMsg:(NSNotification *)notification
{
    NSDictionary *userInfo = notification.userInfo;
    NSString *canScroll = userInfo[@"canScroll"];
    if ([canScroll isEqualToString:@"1"]) {
        _canScroll = YES;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)getNetworkBaseData
{
    //站点ID
    StationInfoEntity *model = [[GetUserStationService sharedService] getSelectStationEntity];
    
    //@状态（全部、供毕、正供、待供）
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeERP];
    [content setModuleType:@"SCDD_HOME_LIST_HEAD_20171017"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    [content setStationID:[model.stationId integerValue]];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        NSArray *rwdArray = nil;
        if(result.resultArray && result.resultArray.count>=2){
            firstArray = [result.resultArray objectAtIndex:0];
            rwdArray = [result.resultArray objectAtIndex:1];
        }
        
        //设置头部页面
        if(firstArray && firstArray.count>0){
            [self.firstResultData removeAllObjects];
            [self.firstResultData addObjectsFromArray:firstArray];
            [self setHeaderViewData:firstArray.firstObject];
            
            CGRect f = self.headImageView.frame;
            f.origin.y= -self.headViewHeight;
            self.headImageView.frame= f;
        }
        
        //设置任务单数
        if(rwdArray && rwdArray.count>0){
            [self.rwdResultData removeAllObjects];
            [self.rwdResultData addObjectsFromArray:rwdArray];
            NSDictionary *dictionary = rwdArray[0];
            
            NSString *CC = [dictionary objectFormatStringForKey:@"正供单数" format:@"%@\n正供" defaults:@"0\n正供"];
            NSString *DM = [dictionary objectFormatStringForKey:@"待供单数" format:@"%@\n待供" defaults:@"0\n待供"];
            NSString *YC = [dictionary objectFormatStringForKey:@"供毕单数" format:@"%@\n供毕" defaults:@"0\n供毕"];
            
            [self.RCSegView setSegmentButtonTitle:CC index:0];
            [self.RCSegView setSegmentButtonTitle:DM index:1];
            [self.RCSegView setSegmentButtonTitle:YC index:2];
        }
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
    }];
}


#pragma make - ScrollView Event

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //处理联动
    //获取滚动视图y值的偏移量
    CGFloat yOffset  = scrollView.contentOffset.y;
    CGFloat tabOffsetY = [mainTableView rectForSection:0].origin.y;
    CGFloat offsetY = scrollView.contentOffset.y;
    
    _isTopIsCanNotMoveTabViewPre = _isTopIsCanNotMoveTabView;
    if (offsetY>=tabOffsetY) {
        scrollView.contentOffset = CGPointMake(0, tabOffsetY);
        _isTopIsCanNotMoveTabView = YES;
    } else {
        _isTopIsCanNotMoveTabView = NO;
    }
    
    if (_isTopIsCanNotMoveTabView != _isTopIsCanNotMoveTabViewPre) {
        if (!_isTopIsCanNotMoveTabViewPre && _isTopIsCanNotMoveTabView) {
            //NSLog(@"滑动到顶端");
            [[NSNotificationCenter defaultCenter] postNotificationName:@"goTop" object:nil userInfo:@{@"canScroll":@"1"}];
            _canScroll = NO;
        }
        if(_isTopIsCanNotMoveTabViewPre && !_isTopIsCanNotMoveTabView){
            //NSLog(@"离开顶端");
            if (!_canScroll) {
                scrollView.contentOffset = CGPointMake(0, tabOffsetY);
            }
        }
    }
    
    /**
     * 处理头部视图
     */
    if(yOffset < -self.headViewHeight) {
        CGRect f = self.headImageView.frame;
        f.origin.y= yOffset ;
        f.size.height= -yOffset;
        f.origin.y= yOffset;
        
        //改变头部视图的fram
        self.headImageView.frame= f;
        //        CGRect avatarF = CGRectMake(f.size.width/2-40, (f.size.height-headViewHeight)+56, 80, 80);
        //        _avatarImage.frame = avatarF;
        //        _countentLabel.frame = CGRectMake((f.size.width-Main_Screen_Width)/2+40, (f.size.height-headViewHeight)+172, Main_Screen_Width-80, 36);
    }
}

- (void)setHeaderViewData:(NSDictionary*)mDictionary
{
    CGFloat jhfl = [mDictionary objectFormatFloatForKey:@"计划方量" retain:1 except:0];
    CGFloat yfhl = [mDictionary objectFormatFloatForKey:@"发货方量" retain:1 except:0];
    
    CGFloat mProgress = (jhfl !=0) ? (yfhl/jhfl) : 0;
    self.loopProgressView.progress = mProgress;
    
    self.RWDSLabel.text = [mDictionary objectFormatStringForKey:@"任务单数量" format:@"%@" defaults:@"0"];
    self.JHFLLabel.text = [NSString stringWithFormat:@"%0.1f", jhfl];
    self.FHFLLabel.text = [mDictionary objectFormatFloatStringForKey:@"发货方量" retain:1 format:@"%@"];
    self.QSFLLabel.text = [mDictionary objectFormatFloatStringForKey:@"签收方量" retain:1 format:@"%@"];
    
    self.ZCCLabel.text = [mDictionary objectFormatStringForKey:@"总车次" format:@"%@" defaults:@"0"];
    self.LTCCLabel.text = [mDictionary objectFormatStringForKey:@"拉砼车次" format:@"%@" defaults:@"0"];
    self.SJCCLabel.text = [mDictionary objectFormatStringForKey:@"砂浆车次" format:@"%@" defaults:@"0"];
    self.LSCCLabel.text = [mDictionary objectFormatStringForKey:@"拉水车次" format:@"%@" defaults:@"0"];
    
}

#pragma make - Station Notification

-(void)updateStationNotification:(StationInfoEntity*)model
{
    //获取页面显示数据
    [self getNetworkBaseData];
    
    //车辆数量
    [self.RCSegView setSegmentButtonTitle:@"0\n正供" index:0];
    [self.RCSegView setSegmentButtonTitle:@"0\n待供" index:1];
    [self.RCSegView setSegmentButtonTitle:@"0\n供毕" index:2];
    
    //车次数据更新
    TPHomeItemViewController *view2 = (TPHomeItemViewController*)[self.RCSegView getChildViewControllerIndex:0];
    TPHomeItemViewController *view1 = (TPHomeItemViewController*)[self.RCSegView getChildViewControllerIndex:1];
    TPHomeItemViewController *view3 = (TPHomeItemViewController*)[self.RCSegView getChildViewControllerIndex:2];
    [view1 updateViewData];
    [view2 updateViewData];
    [view3 updateViewData];
}

#pragma marl -tableDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return SuperHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    //添加pageView
    [cell.contentView addSubview:self.setPageViewControllers];
    
    return cell;
}

/*
 * 这里可以任意替换你喜欢的pageView
 */
-(UIView *)setPageViewControllers
{
    if (!_RCSegView) {
        TPHomeItemViewController * view1= [[TPHomeItemViewController alloc] initWithState:@"正供"];
        TPHomeItemViewController * view2= [[TPHomeItemViewController alloc] initWithState:@"待供"];
        TPHomeItemViewController * view3= [[TPHomeItemViewController alloc] initWithState:@"供毕"];
        
        NSArray *controllers=@[view1,view2,view3];
        NSArray *titleArray =@[@"0\n正供",@"0\n待供",@"0\n供毕"];
        
        MYSegmentView * rcs= [[MYSegmentView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) controllers:controllers titleArray:titleArray ParentController:self lineWidth:SuperWidth/5 lineHeight:3.];
        _RCSegView = rcs;
    }
    return _RCSegView;
}

@end

